﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace UDS.Management
{
    internal class SqlConnectionHolder : IDisposable
    {
        private SqlConnection _conn;

        internal SqlConnectionHolder(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }

            _conn = new SqlConnection(connectionString);
            _conn.Open();
        }

        internal int Execute(string sproc)
        {
            return Execute(sproc, null);
        }

        internal int Execute(string sproc, SqlParameter[] parameters)
        {
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = _conn;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.CommandText = sproc;
            sqlCommand.CommandTimeout = 0;

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    sqlCommand.Parameters.Add(p);
                }
            }

            return sqlCommand.ExecuteNonQuery();
        }

        internal SqlDataReader ExecuteReader(string sproc, SqlParameter[] parameters)
        {
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = _conn;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.CommandText = sproc;
            sqlCommand.CommandTimeout = 0;

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    sqlCommand.Parameters.Add(p);
                }
            }

            return sqlCommand.ExecuteReader();
        }

        internal SqlDataReader ExecuteReader(string sproc)
        {
            return ExecuteReader(sproc, null);
        }

        public void Dispose()
        {
            if (_conn != null)
            {
                _conn.Dispose();
            }
        }
    }
}
